package cn.cloud9.designpattern.dp01singleton;

/**
 * @author OnCloud9
 * @description 懒汉式第二种
 * @project Java
 * @date 2022年05月22日 9:57
 */
public class Singleton4 {
    private Singleton4(){}

    private static Singleton4 instance;

    /**
     * 给方法加锁，同步处理化
     * @return
     */
    public static synchronized Singleton4 getInstance(){
        if (instance == null) {
            // 但是不能保证分配实例也是上锁的
            instance = new Singleton4();
        }
        return instance;
    }

    public static void main(String[] args) {
        class Test implements Runnable {
            @Override
            public void run() {
                final Singleton4 instance = Singleton4.getInstance();
                System.out.println(Thread.currentThread().getName() + " -> " + instance);
            }
        }

        final Thread thread1 = new Thread(new Test());
        final Thread thread2 = new Thread(new Test());
        final Thread thread3 = new Thread(new Test());
        final Thread thread4 = new Thread(new Test());
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        System.out.println(" end ");
        System.out.println();
        /*
         * 需要多执行几次会出现这种情况，判断不稳定
         *  end
         * Thread-0 -> cn.cloud9.designpattern.dp01singleton.Singleton3@1f38108d
         * Thread-1 -> cn.cloud9.designpattern.dp01singleton.Singleton3@5abea0a2
         * */
    }
}
